package com.beiding.my.mql.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FindPrefix {

    private String text;
    private Set<Character> allowChars;
    private String prefix;

    private List<Block> result = new ArrayList<>();

    public FindPrefix(String text, Set<Character> allowChars, String prefix) {
        this.text = text;
        this.allowChars = allowChars;
        this.prefix = prefix;
    }

    public void find() {

        int index = 0;

        List<Position> positions = new ArrayList<>();

        while (true) {
            index = text.indexOf(prefix, index);
            if (index == -1) {
                break;
            } else {
                //方向查找一下判断是否是一个允许的字符集

                if (index > 0) {
                    if (!allowChars.contains(text.charAt(index - 1))) {
                        positions.add(new Position(index));
                    }
                } else {
                    positions.add(new Position(index));
                }

                index += prefix.length();
            }
        }

        for (Position position : positions) {

            int start = position.getIndex() + prefix.length();
            Block block = new Block();
            block.setStart(position.getIndex());
            block.setEnd(text.length() - 1);
            for (int i = start; i < text.length(); i++) {
                char c = text.charAt(i);
                if (!allowChars.contains(c)) {
                    block.setEnd(i - 1);
                    break;
                }
            }
            block.cutText(text);
            result.add(block);
        }
    }

    public List<Block> getResult() {
        return result;
    }

}
